package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseMaterielDetailFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.MaterieListOriginal.MaterieListContent;
import com.isunland.managesystem.entity.OderSaleContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.NumberUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;

public class EditMaterieDetailFragment extends BaseMaterielDetailFragment {

  public static final String EXTRA_CONTENT = "com.isunland.managesystem.entity.EXTRA_CONTENT";
  public static final String EXTRA_ORDER_CONTENT =
      "com.isunland.managesystem.entity.EXTRA_ORDER_CONTENT";
  private MaterieListContent mContent;
  private OderSaleContent orderContent;
  private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

  @Override public void onCreate(Bundle savedInstanceState) {
    mContent = (MaterieListContent) getArguments().getSerializable(EXTRA_CONTENT);
    orderContent = (OderSaleContent) getArguments().getSerializable(EXTRA_ORDER_CONTENT);
    customerId = orderContent != null ? orderContent.getMcustomerId() : "";
    storageId = orderContent != null ? orderContent.getStorageId() : "";
    mainMaterialCode = orderContent != null ? orderContent.getMaterialKindCode() : "";
    kindId = mContent.getMaterialKindCode();
    kindName = mContent.getMaterialKindName();

    super.onCreate(savedInstanceState);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_confirm, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      //保存
      case R.id.menu_item_confirm:

        if (TextUtils.isEmpty(etNumber.getText()) && TextUtils.isEmpty(tvUnitPrice.getText())) {

          ToastUtil.show(R.string.complete_hint);
        } else {
          double number;
          try {
            number = Double.parseDouble(etNumber.getText().toString());
          } catch (NumberFormatException e1) {
            number = 0.0;
          }
          double price;
          try {
            price = Double.parseDouble(tvUnitPrice.getText().toString());
          } catch (NumberFormatException e) {
            price = 0.0;
          }

          //				double result=stockNumber-number;
          //				if (result<0) {
          //					ToastUtil.show(R.string.stock_hint);
          //
          //				}else {
          //					volleyPostSave();

          if (number > 100000000) {
            number = 100000000;
          }
          if (price > 100000000) {
            price = 100000000;
          }
          etNumber.setText(NumberUtil.numberBigToString(number));
          tvUnitPrice.setText(NumberUtil.numberBigToString(price));
          showDialog(SAVE_MATERIEL);
          //				}
        }

        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void volleyPoastSave() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_MATERIE_SAVE);
    //		mContent.setMaterialKindName("");
    //		mContent.setMaterialKindCode("");
    //		mContent.setMaterialName(tvMaterielName.getText().toString());
    ////		mContent.setsInbillCode(tvMaterielCode.getText().toString());
    //		mContent.setMaterialCode(tvMaterielCode.getText().toString());
    //
    //		mContent.setMaterialSelfCode(tvMaterielSelfCode.getText().toString());
    //		mContent.setMtype(tvMaterielType.getText().toString());
    //
    //		mContent.setMunit(tvBaseApartment.getText().toString());
    //		mContent.setMoutPrice(tvUnitPrice.getText().toString());
    //
    //		mContent.setMoutNumber(etNumber.getText().toString());
    //		mContent.setRemark(etNotes.getText().toString());
    //		if (TextUtils.isEmpty(tvUnitPrice.getText().toString())) {
    //			price=0;
    //		}else {
    //			price=Double.parseDouble(tvUnitPrice.getText().toString());
    //		}
    //		mContent.setMoutsumPrice(number*price+"");
    //		HashMap<String,String> mparams=new HashMap<String, String>();
    //		mparams.put("updated","["+new Gson().toJson(mContent)+"]");
    //		LogUtil.i("修改物料参数mparams====" + mparams.toString());

    HashMap<String, String> params = new HashMap<>();
    /**
     * 物料明细默认值
     */

    //		id : ,
    //		memberCode : ,
    //		regStaffId : ,
    //		regStaffName : ,
    //		regDate : ,
    //		sStoragePlaceId : , //所在库房ID
    //		sStoragePlaceName : , //所在库房名称
    //		mainid : //对应的主记录ID
    //		ifReturnAll : 'F' //固定值
    //		discountRate : 100, //折扣率，默认100
    //		mouttaxRate : 0, //税率，默认0

    params.put("id", mContent.getId());
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("regStaffId", mCurrentUser.getJobNumber());
    params.put("regStaffName", mCurrentUser.getRealName());
    params.put("regDate", format.format(new Date()));
    params.put("sStoragePlaceId", orderContent.getStorageId());
    params.put("sStoragePlaceName", orderContent.getStorageName());
    params.put("mainId", orderContent.getId());
    params.put("ifReturnAll", "F");
    params.put("discountRate", "100");
    params.put("mouttaxRate", "0");

    /**
     * 物料明细新增必填字段
     materialKindCode : 物料类别编码，
     materialKindName ：物料类别名称,
     mtype : 规格型号,
     munit : 单位,
     moutNumber : 申请出库数量,
     moutPrice : 单价,
     moutsumPrice : 总价，
     materialCode ： 物料条码，
     materialSelfCode ： 物料自编码
     */
    params.put("materialKindCode", kindId);
    params.put("materialKindName", kindName);
    params.put("materialName", tvMaterielName.getText().toString());
    params.put("materialCode", tvMaterielCode.getText().toString());
    params.put("materialSelfcode", tvMaterielSelfCode.getText().toString());
    params.put("mtype", tvMaterielType.getText().toString());
    params.put("munit", tvBaseApartment.getText().toString());
    params.put("moutPrice", tvUnitPrice.getText().toString());
    params.put("moutNumber", etNumber.getText().toString());
    params.put("outappNumber", etNumber.getText().toString());//标准数量 同 出库数量一致
    params.put("remark", etNotes.getText().toString());
    params.put("conversionRelationship", "1");//固定值
    if (TextUtils.isEmpty(etallPrice.getText().toString())) {
      params.put("moutsumPrice", "0");//总价
    }
    params.put("moutsumPrice", etallPrice.getText().toString());//总价

    HashMap<String, String> mparams = new HashMap<>();
    mparams.put("updated", "[" + new JSONObject(params).toString() + "]");
    LogUtil.i("修改物料params===" + mparams.toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, mparams, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        try {
          LogUtil.i("response=" + arg0);
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
            kindId = "";
            kindName = "";
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
      }
    });
  }

  @Override protected void setTitle() {
    setTitleCustom(R.string.materiel_detail);
  }

  @Override protected void initMaterialData() {
    tvMaterielCategory.setText(mContent.getMaterialKindName());

    tvMaterielName.setText(mContent.getMaterialName());
    //		tvMaterielCode.setText(mContent.getsInbillCode());
    tvMaterielCode.setText(mContent.getMaterialCode());
    tvMaterielSelfCode.setText(mContent.getMaterialSelfCode());
    tvMaterielType.setText(mContent.getMtype());//规格型号
    tvBaseApartment.setText(mContent.getMunit());//基本单位
    tvUnitPrice.setText(NumberUtil.numberBigToString(mContent.getMoutPrice()));//单价
    etNumber.setText(NumberUtil.numberBigToString(mContent.getMoutNumber()));//数量
    //总价
    etallPrice.setText(NumberUtil.numberBigToString(mContent.getMoutsumPrice()));
    etNotes.setText(mContent.getRemark());//备注
    //
    //		llmaterialGone.setVisibility(View.VISIBLE);
    //		tvbatchstorage.setText(mContent.getSinbillBatch());//入库批次
    //		tvProductiondate.setText(mContent.getSmproddate());//生产日期
    //		tvValidityperiod.setText(mContent.getSmexpDate());//有效期

    kindId = mContent.getMaterialKindCode();
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == SAVE_MATERIEL) {
      volleyPoastSave();
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  public static EditMaterieDetailFragment newInstance(MaterieListContent item) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, item);
    EditMaterieDetailFragment fragment = new EditMaterieDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }

  public static EditMaterieDetailFragment newInstance(MaterieListContent item,
      OderSaleContent orderContent) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, item);
    args.putSerializable(EXTRA_ORDER_CONTENT, orderContent);
    EditMaterieDetailFragment fragment = new EditMaterieDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
